package com.qf.Service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.qf.Service.AlipayService;
import com.qf.config.AlipayConfig;
import com.qf.config.MQInit;
import com.qf.entity.Message;
import com.qf.entity.Order;
import com.qf.mapper.MessageMapper;
import com.qf.mapper.OrderMapper;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 作者：大狗
 * 时间：2021/7/13 17:46
 */
@Service
public class AlipayServiceImpl implements AlipayService {
    AlipayClient alipayClient = new DefaultAlipayClient(
            AlipayConfig.gatewayUrl,
            AlipayConfig.app_id,
            AlipayConfig.merchant_private_key,
            AlipayConfig.format,
            AlipayConfig.charset,
            AlipayConfig.alipay_public_key,
            AlipayConfig.sign_type
    );
    //用来存储支付宝返回的商品信息
    Map<String,String> map = new HashMap<>();
    private OrderMapper orderMapper;
    private MessageMapper messageMapper;
    private RabbitTemplate availableTemplate;

    public AlipayServiceImpl(RabbitTemplate availableTemplate,OrderMapper orderMapper, MessageMapper messageMapper) {
        this.orderMapper = orderMapper;
        this.messageMapper = messageMapper;
        this.availableTemplate = availableTemplate;
    }

    @Override
    public String getPayUrl() {
        try {
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
            request.setNotifyUrl("http://qxl.free.idcfengye.com/cost/test");
            //设置待支付的物品
            request.setBizModel(model);
            //订单编号
            model.setOutTradeNo(Long.toString(System.currentTimeMillis()));
            //订单价格
            model.setTotalAmount("11899");
            //订单商品集，参数：字符串
            model.setSubject("iPhone 12 Pro Max 512G");
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            //将支付宝返回的支付信息存在map
            map = JSONObject.parseObject(response.getParams().get("biz_content"), Map.class);
            //创建订单信息
            Order order = new Order();
            order.setUserId(2);
            order.setTotalPrice(BigDecimal.valueOf(Double.valueOf(map.get("total_amount"))));
            //order.setTotalPrice(BigDecimal.valueOf(Double.valueOf("1192")));
            order.setCourseId(2);
            order.setStatus(1);
            order.setCreateTime(new Date());
            order.setOrderId(map.get("out_trade_no"));
            //order.setOrderId("15616165");

            Message message = new Message();
            String messageId = getUUID();
            message.setId(messageId);
            message.setExchange(MQInit.PAY_EXCHANGE);
            message.setRoutingKey(MQInit.PAY_KEY);
            message.setContent(JSONObject.toJSONString(map));
            message.setStatus(0);
            message.setTryCount(0);
            message.setCreateTime(new Date());

            orderMapper.insert(order);
            messageMapper.insert(message);
            /**
             *  CorrelationData 的主要目的是作为 convertAndSend() 方法的第四个参数.
             *  在消息回调的时候 {@link MQInit#rabbitTemplate()} 回调时候, 获取消息的id.
             */
            CorrelationData cd = new CorrelationData(messageId);
            MessageProperties mp = new MessageProperties();
            mp.setCorrelationId(messageId);
            mp.setDeliveryMode(MessageDeliveryMode.PERSISTENT);  // 表示消息为持久化消息
            //设置消息多少秒达到死信交换机 15s
            mp.setExpiration("1500");
            org.springframework.amqp.core.Message msg = new org.springframework.amqp.core.Message(message.getContent().getBytes(), mp);

            // 往RabbitMQ中发送消息(交换机,key,未支付的订单信息,消息id)
            availableTemplate.convertAndSend(MQInit.PAY_EXCHANGE,MQInit.PAY_KEY,msg,cd);

            return response.getQrCode();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "支付失败";
    }

    @Override
    public Object storeData(){
       //成功修改支付状态
        orderMapper.updateStatus(map.get("out_trade_no"));
        return "插入成功!";
    }
    public String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}
